new Vue({
    el: '#system-ini-container',
    data() {
        return {
            editors: {},
            editButtonShow: true,
            originSystemIni: '',
            newSystemIni: '',
            dialogVisible: false,
            versionCompareVisible: false,
            formattedOriginSystemIni: '',
            formattedNewSystemIni: '',
            hasChange: false,
            originSystemIniVersion: '',
            currentSystemIniVersion: '',
        }
    },
    mounted() {
        this.getSystemIni()
    },
    methods: {
         /**
         * 获取system.ini 配置信息
         */
        getSystemIni: function (){
            let self = this;
            axios.get('/-/omso.mon.SystemParams.get_system_ini').then(res => {
                if(res.data.code === 200){
                    const systemIniData = self.jsonToIni(res.data.data)
                    self.loadConfig(systemIniData);
                }else{
                    this.$message({
                        message: res.data.msg,
                        type: 'error'
                    });
                }
            })
            .catch(function (error) {
                 console.log(error);
             });
        },

        /**
         * 递归json 转 ini格式
         * @param obj json字符串
         * @returns {string}
         */
        jsonToIni: function (obj){
            let iniStr = '';
            let count = 0;
            for (const key in obj) {
                if (typeof obj[key] === 'object') {
                    if (count !== 0){
                        iniStr += '\n'
                    }
                    iniStr += `[${key}]\n`;
                    iniStr += this.jsonToIni(obj[key]);
                    count++;
                } else {
                    iniStr += `${key}=${obj[key]}\n`;
                }
            }
            return iniStr;
        },

        /**
         * ace编辑器 展示system.ini
         * @param content 内容
         */
        loadConfig: function (content) {
            const editor = ace.edit(`editor-container`);
            editor.setTheme("ace/theme/twilight");
            editor.session.setMode("/static/js/ini");
            editor.setValue(content, -1);
            editor.setReadOnly(true);
            editor.setOptions({
                enableBasicAutocompletion: true,
                enableSnippets: true,
                enableLiveAutocompletion: true
            });
            ace.require("ace/ext/searchbox")
            this.editors = editor;
            this.originSystemIni = content;
        },

        /**
         * 编辑 system.ini
         */
        ableEdit: function () {
            this.editors.setReadOnly(false);
            this.editButtonShow = !this.editButtonShow
        },

        /**
         * 退出编辑
         */
        escEdit: function (){
            this.editors.setReadOnly(true);
            this.editButtonShow = !this.editButtonShow
        },

        /**
         * 保存内容
         */
        saveAuthorized: function (){
            if(this.hasChange){
                this.saveSystemIni()
            }else{
                this.$confirm('内容未发生更改确认保存？')
                  .then(_ => {
                    this.saveSystemIni()
                  })
                  .catch(_ => {});
            }
        },

        saveSystemIni: function (){
            const editor = this.editors;
            let newSystemConfig = editor.getValue();
            let lines = newSystemConfig.split('\n')
            const configObj = {};
            let currentSection = null;
            lines.forEach(line => {
                line = line.trim()
                if(!line || line.startsWith('#')){
                    return
                }
                if(line.startsWith('[') && line.endsWith(']')){
                    currentSection = line.substring(1, line.length -1)
                    configObj[currentSection] = {}
                }else  if(currentSection){
                    const [key, value] = line.split('=').map(item => item.trim());
                    configObj[currentSection][key] = isNaN(value) ? value : Number(value);
                }
            })
            const configJson = JSON.stringify(configObj, null, 4)
            editor.setReadOnly(true);
         /**
         * 
$query_json('/-/omso.mon.SystemParams.update_system_ini', {systemIniConfig: configJson }).then(res => {
         */   
	axios.post('/-/omso.mon.SystemParams.update_system_ini', {systemIniConfig: configJson }).then(res => {
                if(res.data.code === 200){
                    this.$message({
                        message: res.data.msg,
                        type: 'success'
                    });
                    this.dialogVisible = false
                    this.originSystemIni = ''
                    this.getSystemIni()
                }else{
                    this.$message({
                        message: res.data.msg,
                        type: 'error'
                    });
                }
            })
            .catch(function (error) {
                 console.log(error);
             });
        },

        confirmBeforeSave: function (){
            const editor = this.editors;
            this.newSystemIni = editor.getValue()
            this.formattedOriginSystemIni = this.getFormattedContent(this.originSystemIni, this.originSystemIni)
            this.formattedNewSystemIni = this.getFormattedContent(this.originSystemIni, this.newSystemIni)
            this.dialogVisible = true
        },


        /**
         * system.ini版本对比
         */
        versionCompare: function (){
           let self = this;
           axios.get('/-/omso.mon.SystemParams.system_ini_version_compare').then(res => {
                if(res.data.code === 200){
                    let originSystemIni = res.data.data.origin_config_ini_dict;
                    const originSystemIniFormatted = self.jsonToIni(originSystemIni)
                    let currentSystemIni = res.data.data.config_ini_dict;
                    const currentSystemIniFormatted = self.jsonToIni(currentSystemIni)
                    this.originSystemIniVersion = this.getFormattedContent(originSystemIniFormatted, originSystemIniFormatted)
                    this.currentSystemIniVersion = this.getFormattedContent(originSystemIniFormatted, currentSystemIniFormatted)
                    this.versionCompareVisible = true
                }else{
                    this.$message({
                        message: res.data.msg,
                        type: 'error'
                    });
                }
            })
            .catch(function (error) {
                 console.log(error);
             });
        },

        /**
         * 搜索
         */
        searchContent: function (){
            this.editors.execCommand("find")
        },

        handleClose(done) {
            this.$confirm('确认关闭？')
              .then(_ => {
                done();
              })
              .catch(_ => {});
        },

        /**
         * 版本对比方法
         * @param originContent 原始内容
         * @param newContent 新内容
         * @returns {string} 对比结果
         */
        getFormattedContent(originContent, newContent) {
            const diff = JsDiff.diffLines(originContent, newContent);
            let formattedContent = '';
            diff.forEach(part => {
                const span = document.createElement('span');
                span.textContent = part.value;
                if (part.added) {
                    span.className = 'added';
                    this.hasChange = true;
                } else if (part.removed) {
                    span.className = 'removed';
                    this.hasChange = true;
                } else {
                    span.className = 'unchanged';
                }
                formattedContent += span.outerHTML;
            });
            return formattedContent;
        },
    },
})
